package com.qf.user.manager.service.impl;

import com.qf.common.model.QfUser;
import com.qf.user.manager.bean.LoginUser;
import com.qf.user.manager.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 千锋健哥
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1. 根据用户名到数据库获取用户对象
        QfUser qfUser = userService.getUserByUserName(username);
        if (qfUser == null) {
            throw new UsernameNotFoundException("用户名不存在!");
        }

        //2. 根据用户名到数据库获取权限集合对象
        List<String> menuList = userService.findUserMenuByUserName(username);

        //3. 将用户对象, 权限集合对象封装成UserDetails实体对象
        //封装springSecurity的权限集合对象
        List<SimpleGrantedAuthority> authList = new ArrayList<>();
        for (String menu : menuList) {
            authList.add(new SimpleGrantedAuthority(menu));
        }
        LoginUser loginUser = new LoginUser(qfUser, authList);

        //4. 返回
        return loginUser;
    }

}
